package yc.star.friend.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import yc.star.common.constants.Constant;
import yc.star.common.domain.AppResult;
import yc.star.common.domain.TableDataInfo;
import yc.star.common.enums.ExamListType;
import yc.star.common.security.exception.ApplicationException;
import yc.star.common.security.service.TokenService;
import yc.star.common.utils.ThreadLocalUtil;
import yc.star.friend.domain.exam.Exam;
import yc.star.friend.domain.exam.dto.ExamDTO;
import yc.star.friend.domain.exam.dto.ExamQueryDTO;
import yc.star.friend.domain.exam.vo.ExamVO;
import yc.star.friend.domain.user.UserExam;
import yc.star.friend.manager.ExamCacheManager;
import yc.star.friend.mapper.ExamMapper;
import yc.star.friend.mapper.UserExamMapper;
import yc.star.friend.service.IUserExamService;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserExamServiceImpl implements IUserExamService {

    @Autowired
    private UserExamMapper userExamMapper;
    @Autowired
    private ExamMapper examMapper;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ExamCacheManager examCacheManager;

    @Value("${jwt.secret}")
    private String secret; // jwt安全密钥

    @Override
    public int enter(String token, ExamDTO examDTO) {
        Exam exam = examMapper.selectById(examDTO.getExamId());
        if (exam == null) {
            throw new ApplicationException(AppResult.failed("该竞赛不存在"));
        }
        if (exam.getStartTime().isBefore(LocalDateTime.now())) {
            throw new ApplicationException(AppResult.failed("竞赛已开始无法进行报名"));
        }
        // 从ThreadLocal变量中拿到userId
        Long userId = ThreadLocalUtil.get(Constant.USER_ID, Long.class);
        // 查找是否已经报名过了
        UserExam existUserExam = userExamMapper.selectOne(new LambdaQueryWrapper<UserExam>()
                .eq(UserExam::getUserId, userId)
                .eq(UserExam::getExamId, examDTO.getExamId()));
        if (existUserExam != null) {
            throw new ApplicationException(AppResult.failed("您已经报名过了"));
        }
        // 将报名信息存储到数据库
        UserExam addUserExam = new UserExam();
        addUserExam.setExamId(examDTO.getExamId());
        addUserExam.setUserId(userId);
        int rows = userExamMapper.insert(addUserExam);
        // 将报名信息存储到redis中
        examCacheManager.addUserExamCache(userId,examDTO.getExamId());
        return rows;
    }

    @Override
    public TableDataInfo list(ExamQueryDTO examQueryDTO) {
        // 拿到userId
        Long userId = ThreadLocalUtil.get(Constant.USER_ID, Long.class);
        // 拿到redis中用户竞赛的列表长度
        Long listSize = examCacheManager.getListSize(ExamListType.USER_EXAM_LIST.getValue(),userId);
        List<ExamVO> examVOList;
        if (listSize == null || listSize == 0) {
            // redis缓存列表中没有数据
            PageHelper.startPage(examQueryDTO.getPageNum(),examQueryDTO.getPageSize());
            examVOList = userExamMapper.selectUserExamList(userId); // 从数据库中将竞赛列表信息查出
            examCacheManager.refreshCache(ExamListType.USER_EXAM_LIST.getValue(),userId); // 刷新缓存，将数据同步到缓存中
            listSize = new PageInfo<>(examVOList).getTotal();
        } else {
            examQueryDTO.setType(ExamListType.USER_EXAM_LIST.getValue());
            // redis缓存中有数据,就直接从redis中查询
            examVOList = examCacheManager.getExamVOList(examQueryDTO,userId);
            listSize = examCacheManager.getListSize(examQueryDTO.getType(),userId);
        }
        if (CollectionUtil.isEmpty(examVOList)) {
            return TableDataInfo.empty();
        }
        return TableDataInfo.success(examVOList,listSize);
    }

}